package com.onLineCar.driver.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * OCR身份证图片内容提取工具类
 */
public class OCRUtils {

    private static String host = "https://ocrapi-document.taobao.com";
    private static String path = "/ocrservice/document";
    private static String method = "POST";
    private static String appcode="5d600475e82a4572a97488d3184ccb64";
    public static Map<String, String> parseIdCardInfo( String imageUrl) throws Exception {

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        headers.put("Content-Type", "application/json; charset=UTF-8");

        Map<String, String> querys = new HashMap<>();
        //String bodys = "{\"img\":\"\",\"url\":\"\",\"prob\":false}";
        //传入身份证图片地址
        String bodys = "{\"url\":\"" + imageUrl + "\"}";

        //调用阿里云API
        HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
        String string = EntityUtils.toString(response.getEntity());
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            JsonNode rootNode = objectMapper.readTree(string);
            String content = rootNode.get("content").asText();
            String strWithoutSpaces = content.replace(" ", "");


            //根据关键字提取身份证信息
            String name = strWithoutSpaces.split("姓名")[1].split("性别")[0];
            String gender = strWithoutSpaces.split("性别")[1].split("民族")[0];
            String nationality = strWithoutSpaces.split("民族")[1].split("出生")[0];
            String birthday = strWithoutSpaces.split("出生")[1].split("住址")[0];
            String address = strWithoutSpaces.split("住址")[1].split("公民身份号码")[0];
            String idNumber = strWithoutSpaces.split("公民身份号码")[1];

            //添加到返回
            Map<String, String> idCardInfo = new HashMap<>();
            //姓名
            idCardInfo.put("name", name);
            //性别
            idCardInfo.put("gender", gender);
            //出生日期
            idCardInfo.put("nationality", nationality);
            //民族
            idCardInfo.put("birthday", birthday);
            //详细住址
            idCardInfo.put("address", address);
            //身份证号
            idCardInfo.put("idNumber", idNumber);
            //返回结果
            return idCardInfo;
        } catch (Exception e) {
            throw new Exception("Failed to parse ID card information.");
        }
    }
}
